package the.broccoli.weixin.service.support;

import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpMessageHandler;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutTextMessage;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import the.broccoli.weixin.service.dto.WeiXinMpSubscribeDTO;

import javax.annotation.Resource;
import java.util.Map;

@Component
@Slf4j
public class SubscribeSupport implements WxMpMessageHandler {

    @Resource
    private WxMpService wxMpService;

    @ConditionalOnMissingBean
    @Bean
    public MpSubscribeService mpSubscribeService() {
        return MpSubscribeService.Default.getInstance();
    }

    @Resource
    private MpSubscribeService mpSubscribeService;

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, Map<String, Object> context,
                                    WxMpService wxMpService, WxSessionManager sessionManager) {
        WxMpXmlOutTextMessage m
                = WxMpXmlOutMessage.TEXT()
                .content("感谢您的关注！")
                .fromUser(wxMessage.getToUser())
                .toUser(wxMessage.getFromUser())
                .build();

        WxMpUser wxMpUser = getUserInfo(wxMessage.getFromUser(), "zh_CN");
        log.info("wxMpUser:" + wxMpUser.toString());
        WeiXinMpSubscribeDTO dto = new WeiXinMpSubscribeDTO();
        dto.setOpenId(wxMessage.getFromUser());
        dto.setUnionId(wxMpUser.getUnionId());
        mpSubscribeService.subscribe(dto);
        return m;
    }

    public WxMpUser getUserInfo(String openid, String lang) {
        WxMpUser wxMpUser = null;
        try {
            wxMpUser = this.wxMpService.getUserService().userInfo(openid, lang);
        } catch (WxErrorException e) {
            log.error(e.getError().toString());
        }
        return wxMpUser;
    }
}
